using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Diagnostics;

namespace FeatureWally.Client {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();

            tbSearchWord.Text = Common.Constant.SearchFieldText;
            cbSearchScope.Items.Add("Web only");
            cbSearchScope.Items.Add("Site collection");
            cbSearchScope.Items.Add("Feature definitions");
            cbSearchScope.Items.Add("Web Application");
            cbSearchScope.Items.Add("Farm");
            cbSearchScope.Enabled = false;
        }

        private void button2_Click(object sender, EventArgs e) {
            if (tbSearchWord.Text.Equals(string.Empty) || tbSearchWord.Text.Equals(Common.Constant.SearchFieldText)) {
                MessageBox.Show(Common.Constant.Messages.EnterSearchWord);
            }
            else {
                if (tbUrl.Text.Equals(string.Empty)) {
                    MessageBox.Show(Common.Constant.Messages.EnterUrl);
                }
                else {
                    try {
                        cbSearchScope.Enabled = false;
                        tbSearchWord.Enabled = false;
                        tbUrl.Enabled = false;
                        btnSearch.Enabled = false;
                        Cursor.Current = Cursors.WaitCursor;
                        treeViewFeatureList.Nodes.Clear();
                        menuStrip1.Enabled = false;
                        Application.DoEvents();

                        AddLogEntry(Common.Constant.Log.SearchStart);
                        FWSearch search = new FWSearch(tbSearchWord.Text.Trim(), tbUrl.Text);

                        TreeNode tnSearchNode = new TreeNode(string.Format(Common.Constant.TreeNodes.SearchRoot, search.SearchWord));
                        tnSearchNode.Tag = search;
                        tnSearchNode.ImageIndex = 0;

                        

                        using (SPSite searchSite = new SPSite(search.SearchUrl)) {
                            SearchFarmFeatureDefinitions(searchSite, search);
                            SearchFeatureActivations(searchSite, search);

                            UI.Controls.FWNodeScope tnScopeFarm = new UI.Controls.FWNodeScope(Common.Constant.TreeNodes.ScopeFarm, 1);
                            UI.Controls.FWNodeScope tnScopeWebApplication = new UI.Controls.FWNodeScope(Common.Constant.TreeNodes.ScopeWebApplication, 2);
                            UI.Controls.FWNodeScope tnScopeSiteCollection = new UI.Controls.FWNodeScope(Common.Constant.TreeNodes.ScopeSiteCollection, 3);
                            UI.Controls.FWNodeScope tnScopeWeb = new UI.Controls.FWNodeScope(Common.Constant.TreeNodes.ScopeWeb, 4);
                            TreeNode tnScopeInvalid = new TreeNode(Common.Constant.TreeNodes.ScopeInvalid, 5, 5);
                            UI.Controls.FWNodeScope tnDefinitionError = new UI.Controls.FWNodeScope(Common.Constant.TreeNodes.ProblemFeatures, 6);
                            foreach (DictionaryEntry deFeatureDefinition in search.FeatureDefinitions) {
                                FWFeatureDefinition fwfd = (FWFeatureDefinition)deFeatureDefinition.Value;
                                UI.Controls.FWNodeFeature featureNode = new UI.Controls.FWNodeFeature(fwfd);

                                foreach (string activatedAt in fwfd.ActivatedAt) {
                                    TreeNode tnActivatedAt = new TreeNode(activatedAt, 8, 8);
                                    featureNode.Nodes.Add(tnActivatedAt);
                                }
                                try {
                                    switch (fwfd.Definition.Scope) {
                                        case SPFeatureScope.Farm: tnScopeFarm.Nodes.Add(featureNode); break;
                                        case SPFeatureScope.WebApplication: tnScopeWebApplication.Nodes.Add(featureNode); break;
                                        case SPFeatureScope.Site: tnScopeSiteCollection.Nodes.Add(featureNode); break;
                                        case SPFeatureScope.Web: tnScopeWeb.Nodes.Add(featureNode); break;
                                        default:
                                            UI.Controls.FWNodeFeatureError tnFeatureError = new UI.Controls.FWNodeFeatureError(fwfd);
                                            tnScopeInvalid.Nodes.Add(tnFeatureError); break;
                                    }
                                }
                                catch {
                                    UI.Controls.FWNodeFeatureError tnFeatureError = new UI.Controls.FWNodeFeatureError(fwfd);
                                    tnDefinitionError.Nodes.Add(tnFeatureError);
                                }
                            }
                            tnScopeFarm.Text += " (" + tnScopeFarm.Nodes.Count.ToString() + ")";
                            tnScopeWebApplication.Text += " (" + tnScopeWebApplication.Nodes.Count.ToString() + ")";
                            tnScopeSiteCollection.Text += " (" + tnScopeSiteCollection.Nodes.Count.ToString() + ")";
                            tnScopeWeb.Text += " (" + tnScopeWeb.Nodes.Count.ToString() + ")";
                            tnScopeInvalid.Text += " (" + tnScopeInvalid.Nodes.Count.ToString() + ")";
                            tnDefinitionError.Text += " (" + tnDefinitionError.Nodes.Count.ToString() + ")";
                            tnSearchNode.Nodes.Add(tnScopeFarm);
                            tnSearchNode.Nodes.Add(tnScopeWebApplication);
                            tnSearchNode.Nodes.Add(tnScopeSiteCollection);
                            tnSearchNode.Nodes.Add(tnScopeWeb);
                            tnSearchNode.Nodes.Add(tnScopeInvalid);
                            tnSearchNode.Nodes.Add(tnDefinitionError);
                            tnSearchNode.Expand();
                        }
                        treeViewFeatureList.Nodes.Add(tnSearchNode);
                        treeViewFeatureList.SelectedNode = tnSearchNode;
                    }
                    catch (Exception exc) {
                        MessageBox.Show(string.Format(Common.Constant.Messages.UnexpectedError, exc.ToString()));
                    }
                    finally {
                        AddLogEntry(Common.Constant.Log.SearchEnd);

                        menuStrip1.Enabled = true;
                        tbSearchWord.Enabled = true;
                        tbUrl.Enabled = true;
                        btnSearch.Enabled = true;
                        Cursor.Current = Cursors.Default;
                    }
                }
            }
        }

        private void SearchFarmFeatureDefinitions(SPSite site, FWSearch search) {
            AddLogEntry(Common.Constant.Log.SearchingFeatureDefinitions);
            foreach (SPFeatureDefinition spfd in site.WebApplication.Farm.FeatureDefinitions) {

                if (search.IsMatch(spfd)) {
                    search.FeatureDefinitions.Add(spfd.Id, new FWFeatureDefinition(spfd));
                }
            }
        }

        private void SearchFeatureActivations(SPSite searchSite, FWSearch search) {
            foreach (SPService service in searchSite.WebApplication.Farm.Services) {
                if (service is SPWebService) {
                    SPWebService webservice = (SPWebService)service;
                    foreach (SPFeature wsfeature in webservice.Features) {
                        if (search.IsMatch(wsfeature.Definition)) {
                            search.AddActivation(wsfeature, webservice.Farm.DisplayName);
                        }
                    }
                    foreach (SPWebApplication webapplication in webservice.WebApplications)
                    {
                        try
                        {
                            AddLogEntry(string.Format(Common.Constant.Log.SearchingWebApplication, webapplication.DisplayName));
                            foreach (SPFeature waFeature in webapplication.Features)
                            {
                                if (search.IsMatch(waFeature.Definition))
                                    search.AddActivation(waFeature, webapplication.AlternateUrls[0].Uri.ToString());
                            }
                            SPSecurity.RunWithElevatedPrivileges(delegate()
                            {
                                AddLogEntry(Common.Constant.Log.SearchingSiteCollections);
                                foreach (SPSite site in webapplication.Sites)
                                {
                                    try
                                    {
                                        foreach (SPFeature sFeature in site.Features)
                                        {
                                            try
                                            {
                                                if (search.IsMatch(sFeature.Definition))
                                                    search.AddActivation(sFeature, site.Url);
                                            }
                                            catch
                                            {
                                                continue;
                                            }

                                        }
                                        AddLogEntry(Common.Constant.Log.SearchingWebs);
                                        foreach (SPWeb web in site.AllWebs)
                                        {
                                            try
                                            {
                                                foreach (SPFeature wFeature in web.Features)
                                                {
                                                    try
                                                    {
                                                        if (search.IsMatch(wFeature.Definition))
                                                            search.AddActivation(wFeature, web.Url);
                                                    }
                                                    catch
                                                    {
                                                        continue;
                                                    }
                                                }
                                                web.Dispose();
                                            }
                                            catch
                                            {
                                                continue;
                                            }
                                        }
                                        site.Dispose();
                                    }
                                    catch(Exception e)
                                    {
                                        AddLogEntry(string.Format(Common.Constant.Log.ErrorInLoadingWebApplication, webapplication.DisplayName, e.Message));
                                        continue;
                                    }
                                }
                            });
                        }
                        catch
                        {
                            continue;
                        }
                    }
                    
                }
            }
        }

        private void AddLogEntry(string txt) {
            tbLog.Text += string.Format("{0}: {1}\r\n", DateTime.Now.ToLongTimeString(), txt);
            tbLog.SelectionStart = tbLog.Text.Length;
            tbLog.ScrollToCaret();
            Application.DoEvents();
        }

        

        private void treeViewFeatureList_AfterSelect(object sender, TreeViewEventArgs e) {
            propertyGrid1.SelectedObject = e.Node.Tag;
            tbFeatureXml.Text = string.Empty;
            tbStsAdm.Text = string.Empty;
            cbStsAdm_Deactivate.Enabled = false;
            cbStsAdm_UnInstall.Enabled = false;
            btnStsAdmRun.Enabled = false;
            btnStsAdmSaveFile.Enabled = false;
            if (e.Node is UI.Controls.FWNodeFeature) {
                tbFeatureXml.Text = ((UI.Controls.FWNodeFeature)e.Node).GetFeatureXml();
                tbStsAdm.Text = ((UI.Controls.FWNodeFeature)e.Node).GetStsAdm(true, cbStsAdm_Deactivate.Checked, cbStsAdm_UnInstall.Checked);
                cbStsAdm_Deactivate.Enabled = true;
                cbStsAdm_UnInstall.Enabled = true;
                btnStsAdmRun.Enabled = true;
                btnStsAdmSaveFile.Enabled = true;
            }
            if (e.Node is UI.Controls.FWNodeScope) {
                tbStsAdm.Text = ((UI.Controls.FWNodeScope)e.Node).GetStsAdm(true, cbStsAdm_Deactivate.Checked, cbStsAdm_UnInstall.Checked);
                cbStsAdm_Deactivate.Enabled = true;
                cbStsAdm_UnInstall.Enabled = true;
                btnStsAdmRun.Enabled = true;
                btnStsAdmSaveFile.Enabled = true;
            }
        }

        
        private void treeViewFeatureList_MouseDown(object sender, MouseEventArgs e) {
            treeViewFeatureList.ContextMenuStrip = null;
            if (e.Button == MouseButtons.Right) {
                TreeNode tnTest = treeViewFeatureList.GetNodeAt(e.X, e.Y);
                if (tnTest != null) {
                    treeViewFeatureList.SelectedNode = tnTest;

                    if (tnTest is UI.Controls.FWNodeFeature) {
                        deActivateToolStripMenuItem.Visible = (tnTest.Nodes.Count > 0);
                        uninstallToolStripMenuItem.Visible = (tnTest.Nodes.Count == 0);
                        deActivateAllToolStripMenuItem.Visible = false;
                        unInstallAllToolStripMenuItem.Visible = false;
                        createDummyDefinitionToolStripMenuItem.Visible = false;
                        treeViewFeatureList.ContextMenuStrip = contextMenuStrip1;
                    }
                    else if (tnTest is UI.Controls.FWNodeFeatureError) {
                        if (((UI.Controls.FWNodeFeatureError)treeViewFeatureList.SelectedNode).DummyFileCreated) {
                            deActivateToolStripMenuItem.Visible = false;
                            uninstallToolStripMenuItem.Visible = true;
                            deActivateAllToolStripMenuItem.Visible = false;
                            unInstallAllToolStripMenuItem.Visible = false;
                            createDummyDefinitionToolStripMenuItem.Visible = false;
                            treeViewFeatureList.ContextMenuStrip = contextMenuStrip1;
                        }
                        else {
                            deActivateToolStripMenuItem.Visible = false;
                            uninstallToolStripMenuItem.Visible = false;
                            createDummyDefinitionToolStripMenuItem.Visible = true;
                            deActivateAllToolStripMenuItem.Visible = false;
                            unInstallAllToolStripMenuItem.Visible = false;
                            treeViewFeatureList.ContextMenuStrip = contextMenuStrip1;
                        }
                    }
                    else if (tnTest is UI.Controls.FWNodeScope) {
                        deActivateToolStripMenuItem.Visible = false;
                        uninstallToolStripMenuItem.Visible = false;
                        createDummyDefinitionToolStripMenuItem.Visible = false;
                        deActivateAllToolStripMenuItem.Visible = AnyActivations(tnTest);
                        unInstallAllToolStripMenuItem.Visible = !AnyActivations(tnTest);
                        treeViewFeatureList.ContextMenuStrip = contextMenuStrip1;
                    }
                }
            }
        }

        private bool AnyActivations(TreeNode scope) {
            bool any = false;
            if (scope.Nodes.Count > 0) {
                for (int i = 0; i < scope.Nodes.Count; i++) {
                    if (scope.Nodes[i].Nodes.Count > 0) {
                        any = true;
                    }
                }
            }
            return any;
        }









        #region Main Menu - File - Events

        private void exitToolStripMenuItem_Click(object sender, EventArgs e) {
            SaveSettings();
            Application.Exit();
        }

        #endregion

        #region Main Menu - Edit - Events

        private void pasteToolStripMenuItem_Click(object sender, EventArgs e) {
            TextBoxBase control = Handlers.ShortCutHandler.Current.GetMyCommandObject(Handlers.FWEditCommand.Paste);
            if (control != null)
                control.Paste();
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e) {
            TextBoxBase control = Handlers.ShortCutHandler.Current.GetMyCommandObject(Handlers.FWEditCommand.Copy);
            if (control != null)
                control.Copy();
        }

        private void cutToolStripMenuItem_Click(object sender, EventArgs e) {
            TextBoxBase control = Handlers.ShortCutHandler.Current.GetMyCommandObject(Handlers.FWEditCommand.Cut);
            if (control != null)
                control.Cut();
        }

        private void undoToolStripMenuItem_Click(object sender, EventArgs e) {
            TextBoxBase control = Handlers.ShortCutHandler.Current.GetMyCommandObject(Handlers.FWEditCommand.Undo);
            if (control != null)
                control.Undo();
        }

        private void redoToolStripMenuItem_Click(object sender, EventArgs e) {
        }

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e) {
            TextBoxBase control = Handlers.ShortCutHandler.Current.GetMyCommandObject(Handlers.FWEditCommand.SelectAll);
            if (control != null)
                control.SelectAll();
        }

        #endregion

        #region Main Menu - Tools - Events

        private void advancedSearchToolStripMenuItem_Click(object sender, EventArgs e) {
            if (panelSearchForm.Height == 29) {
                panelSearchForm.Height = 58;
                advancedSearchToolStripMenuItem.Text = "Basic search";
            }
            else {
                panelSearchForm.Height = 29;
                advancedSearchToolStripMenuItem.Text = "Advanced search";
            }
        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e) {
            UI.Forms.WindowOptions winOptions = new UI.Forms.WindowOptions();
            winOptions.ShowDialog(this);
        }

        #endregion

        #region Main Menu - Help - Events

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e) {
            UI.Forms.AboutWally win = new UI.Forms.AboutWally();
            win.ShowDialog();
        }

        #endregion

        #region TextBox Leave/Enter Events

        private void tbSearchWord_Enter(object sender, EventArgs e) {
            Handlers.ShortCutHandler.Current.RegisterCommand(tbSearchWord, Handlers.FWEditCommand.Cut, cutToolStripMenuItem);
            Handlers.ShortCutHandler.Current.RegisterCommand(tbSearchWord, Handlers.FWEditCommand.Copy, copyToolStripMenuItem);
            Handlers.ShortCutHandler.Current.RegisterCommand(tbSearchWord, Handlers.FWEditCommand.Paste, pasteToolStripMenuItem);
            Handlers.ShortCutHandler.Current.RegisterCommand(tbSearchWord, Handlers.FWEditCommand.Undo, undoToolStripMenuItem);
            Handlers.ShortCutHandler.Current.RegisterCommand(tbSearchWord, Handlers.FWEditCommand.SelectAll, selectAllToolStripMenuItem);

            if (tbSearchWord.Text.Equals(Common.Constant.SearchFieldText))
                tbSearchWord.Text = "";
        }

        private void tbSearchWord_Leave(object sender, EventArgs e) {
            Handlers.ShortCutHandler.Current.ClearCommands();

            if (tbSearchWord.Text.Equals(string.Empty))
                tbSearchWord.Text = Common.Constant.SearchFieldText;
        }

        private void tbStsAdm_Enter(object sender, EventArgs e) {
            Handlers.ShortCutHandler.Current.RegisterCommand(tbStsAdm, Handlers.FWEditCommand.Copy, copyToolStripMenuItem);
            Handlers.ShortCutHandler.Current.RegisterCommand(tbStsAdm, Handlers.FWEditCommand.SelectAll, selectAllToolStripMenuItem);
        }

        private void tbStsAdm_Leave(object sender, EventArgs e) {
            Handlers.ShortCutHandler.Current.ClearCommands();
        }

        private void tbUrl_Enter(object sender, EventArgs e) {
            Handlers.ShortCutHandler.Current.RegisterCommand(tbUrl, Handlers.FWEditCommand.Cut, cutToolStripMenuItem);
            Handlers.ShortCutHandler.Current.RegisterCommand(tbUrl, Handlers.FWEditCommand.Copy, copyToolStripMenuItem);
            Handlers.ShortCutHandler.Current.RegisterCommand(tbUrl, Handlers.FWEditCommand.Paste, pasteToolStripMenuItem);
            Handlers.ShortCutHandler.Current.RegisterCommand(tbUrl, Handlers.FWEditCommand.Undo, undoToolStripMenuItem);
            Handlers.ShortCutHandler.Current.RegisterCommand(tbUrl, Handlers.FWEditCommand.SelectAll, selectAllToolStripMenuItem);
        }

        private void tbUrl_Leave(object sender, EventArgs e) {
            Handlers.ShortCutHandler.Current.ClearCommands();
        }

        private void tbLog_Enter(object sender, EventArgs e) {
            Handlers.ShortCutHandler.Current.RegisterCommand(tbLog, Handlers.FWEditCommand.Copy, copyToolStripMenuItem);
            Handlers.ShortCutHandler.Current.RegisterCommand(tbLog, Handlers.FWEditCommand.SelectAll, selectAllToolStripMenuItem);
        }

        private void tbLog_Leave(object sender, EventArgs e) {
            Handlers.ShortCutHandler.Current.ClearCommands();
        }

        private void tbFeatureXml_Enter(object sender, EventArgs e) {
            Handlers.ShortCutHandler.Current.RegisterCommand(tbFeatureXml, Handlers.FWEditCommand.Copy, copyToolStripMenuItem);
            Handlers.ShortCutHandler.Current.RegisterCommand(tbFeatureXml, Handlers.FWEditCommand.SelectAll, selectAllToolStripMenuItem);
        }

        private void tbFeatureXml_Leave(object sender, EventArgs e) {
            Handlers.ShortCutHandler.Current.ClearCommands();
        }

        #endregion

        #region Application Events

        public void Application_ApplicationExit(object sender, EventArgs e) {
            SaveSettings();
        }

        #endregion

        #region Form Events

        private void Form1_Resize(object sender, EventArgs e) {
            panelLog.Height = Convert.ToInt32(Math.Floor((this.ClientSize.Height * 0.25)));
        }

        private void Form1_Load(object sender, EventArgs e) {
            panelSearchForm.Height = 29;
        }

        #endregion

        #region TreeView Feature - Events



        #endregion

        #region ContextMenu - TreeView - Events

        private void createDummyDefinitionToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                UI.Controls.FWNodeFeatureError node = (UI.Controls.FWNodeFeatureError)treeViewFeatureList.SelectedNode;
                node.CreateDummyDefinitionFile();
            }
            catch (Exception exc) {
                MessageBox.Show("An error occurred while creating the dummy file");
                AddLogEntry(exc.ToString());
            }
        }

        private void uninstallToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                TreeNode node = treeViewFeatureList.SelectedNode;
                SPFeatureDefinition def = null;
                if (node is UI.Controls.FWNodeFeature)
                    def = ((UI.Controls.FWNodeFeature)node).Definition.Definition;
                else if (node is UI.Controls.FWNodeFeatureError)
                    def = ((UI.Controls.FWNodeFeatureError)node).Definition.Definition;
                if (def != null) {
                    def.Delete();
                    MessageBox.Show("Feature has been uninstalled succesfully");
                    node.Remove();
                }

            }
            catch (Exception exc) {
                MessageBox.Show("An error occurred while uninstalling the feature");
                AddLogEntry(exc.ToString());
            }
        }

        private void deActivateToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                MessageBox.Show("Not implemented yet");
            }
            catch (Exception exc) {
               throw; 
            }
        }

        private void unInstallAllToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                MessageBox.Show("Not implemented yet");
            }
            catch (Exception exc) {
               throw; 
            }
        }

        private void deActivateAllToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                MessageBox.Show("Not implemented yet");
            }
            catch (Exception exc) {
               throw; 
            }
        }

        #endregion

        #region StsAdm Tab Events

        private void cbStsAdm_Deactivate_CheckedChanged(object sender, EventArgs e) {
            if (cbStsAdm_Deactivate.Focused) {
                tbStsAdm.Text = string.Empty;
                if (treeViewFeatureList.SelectedNode is UI.Controls.FWNodeFeature) {
                    tbStsAdm.Text = ((UI.Controls.FWNodeFeature)treeViewFeatureList.SelectedNode).GetStsAdm(true, cbStsAdm_Deactivate.Checked, cbStsAdm_UnInstall.Checked);
                }
                if (treeViewFeatureList.SelectedNode is UI.Controls.FWNodeScope) {
                    tbStsAdm.Text = ((UI.Controls.FWNodeScope)treeViewFeatureList.SelectedNode).GetStsAdm(true, cbStsAdm_Deactivate.Checked, cbStsAdm_UnInstall.Checked);
                }
            }
        }

        private void cbStsAdm_UnInstall_CheckedChanged(object sender, EventArgs e) {
            if (cbStsAdm_UnInstall.Focused) {
                tbStsAdm.Text = string.Empty;
                if (treeViewFeatureList.SelectedNode is UI.Controls.FWNodeFeature) {
                    tbStsAdm.Text = ((UI.Controls.FWNodeFeature)treeViewFeatureList.SelectedNode).GetStsAdm(true, cbStsAdm_Deactivate.Checked, cbStsAdm_UnInstall.Checked);
                }
                if (treeViewFeatureList.SelectedNode is UI.Controls.FWNodeScope) {
                    tbStsAdm.Text = ((UI.Controls.FWNodeScope)treeViewFeatureList.SelectedNode).GetStsAdm(true, cbStsAdm_Deactivate.Checked, cbStsAdm_UnInstall.Checked);
                }
            }
        }

        private void btnStsAdmSaveFile_Click(object sender, EventArgs e) {
            try {
                string text2save = tbStsAdm.Text;
                saveFileStsAdm.InitialDirectory = Properties.Settings.Default.StsAdmExportLocation;
                saveFileStsAdm.RestoreDirectory = false;
                DialogResult result = saveFileStsAdm.ShowDialog(this);
                if (result == DialogResult.OK) {
                    using (Stream stream = saveFileStsAdm.OpenFile()) {
                        using (StreamWriter writer = new StreamWriter(stream)) {
                            writer.Write(text2save);
                        }
                    }
                }
            }
            catch (Exception exc) {
                MessageBox.Show("An error occurred while exporting the bat file. View log for details.");
                AddLogEntry("Save bat file failed: " + exc.ToString());
            }
        }

        private void btnStsAdmRun_Click(object sender, EventArgs e) {
            btnStsAdmRun.Enabled = false;
            try {

                // Save temporary bat file first.
                string text2save = tbStsAdm.Text;
                string savepath = Application.StartupPath + "\\temp";
                if (!Directory.Exists(savepath)) {
                    Directory.CreateDirectory(savepath);
                }
                using (StreamWriter writer = File.CreateText(savepath + "\\fw.bat")) {
                    writer.Write(text2save);
                }

                using (Process v = new Process()) {
                    v.StartInfo = new ProcessStartInfo(savepath + "\\fw.bat");
                    v.StartInfo.RedirectStandardOutput = true;
                    v.StartInfo.RedirectStandardInput = false;
                    v.StartInfo.RedirectStandardError = true;
                    v.StartInfo.UseShellExecute = false;
                    v.StartInfo.CreateNoWindow = true;

                    v.Start();

                    tbStsAdmCommandWindow.Text = v.StandardOutput.ReadToEnd();
                    tbStsAdmCommandWindow.Text += v.StandardError.ReadToEnd();

                    v.WaitForExit();
                }
            }
            catch (Exception exc) {
                AddLogEntry(exc.ToString());
            }
            btnStsAdmRun.Enabled = true;
        }

        #endregion

        private void cbUseDefaultCredentials_CheckedChanged(object sender, EventArgs e) {
            if (cbUseDefaultCredentials.Focused) {
                tbCustomPassword.Enabled = !cbUseDefaultCredentials.Checked;
                tbCustomUsername.Enabled = !cbUseDefaultCredentials.Checked;
            }
        }

        private void SaveSettings() {
            try {
            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }
        }
        

        

        



        

        

        

    }
}